package com.fy.oa.zc.crm;

import com.fy.oa.zc.conf.FyOAConf;
import com.fy.oa.zc.domain.FySummaryView;
import com.fy.oa.zc.exception.FyOAException;
import com.fy.oa.zc.manager.AFyOA_FormEventManager;
import com.fy.oa.zc.manager.FyOA_FormEventManager;
import com.fy.oa.zc.soap.client.FyOA_SOAPClient;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.jdbc.core.JdbcTemplate;

public final class FyOA2CRM_CustomerChange_ManagerImpl
  extends AFyOA_FormEventManager
  implements FyOA_FormEventManager
{
  private static final Log logger = LogFactory.getLog(FyOA2CRM_CustomerChange_ManagerImpl.class);
  private FyOA_SOAPClient fyOA_SOAPClient;
  private static final String QUERYMESSAGE_PROCESS_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere (a.AFFAIR_ID,a.CREATE_DATE) in ( select a1.affair_id,max(a1.create_date) from CTP_COMMENT_ALL a1 where a1.AFFAIR_ID=? group by a1.affair_id)  and rownum = 1";
  private static final String QUERYMESSAGE_STOP_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.termination' and rownum =1";
  private static final String QUERYMESSAGE_CANCEL_SQL = "select p.NAME||'/'||m.name member from ORG_MEMBER m left join ORG_POST p on m.ORG_POST_ID = p.id where m.id =?";
  private static final String QUERYMESSAGE_STEPBACK_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.rollback' and rownum =1";
  private static final String XMLTEMPLATE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cus=\"http://siebel.com/CustomUI\"><soapenv:Header>\n<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">\n<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">\n<wsse:Username>GUESTERM</wsse:Username>\n<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>\n</wsse:UsernameToken>\n</wsse:Security>\n</soapenv:Header>\n   <soapenv:Body>\n      <cus:FYOAApproveServiceAccntChangeApprove_Input>\n         <cus:Accountfinalstatus></cus:Accountfinalstatus>\n         <cus:AccounId></cus:AccounId>\n\t\t\t<cus:Accountmessage></cus:Accountmessage>\n         <cus:Accountposition></cus:Accountposition>\n <cus:RecordId></cus:RecordId>         <cus:Oacreateddatetime></cus:Oacreateddatetime>\n      </cus:FYOAApproveServiceAccntChangeApprove_Input>\n   </soapenv:Body>\n</soapenv:Envelope>";
  
  public String toString()
  {
    return "客户变更审批";
  }
  
  private void resultParse(String xml)
  {
    try
    {
      logger.info(">>>>>>>>>>>>>>>>>>>>>>>" + xml);
      Document doc = DocumentHelper.parseText(xml);
      doc.getRootElement().addNamespace("siebelf", "http://www.siebel.com/ws/fault");
      doc.getRootElement().addNamespace("ns", "http://siebel.com/CustomUI");
      List<?> list = doc.selectNodes("//ns:ErrorMessage");
      if (list.size() == 1)
      {
        Element node = (Element)list.get(0);
        String msg = node.getText();
        if ((msg != null) && (!"".equals(msg))) {
          throw new FyOAException("客户变更审批信息写入CRM失败，错误提示为：" + msg);
        }
      }
      else
      {
        if (list.size() == 0)
        {
          list = doc.selectNodes("//siebelf:errormsg");
          if (list.size() == 1) {
            throw new FyOAException("客户变更授信审批信息写入CRM失败，错误提示为：" + ((Element)list.get(0)).getText());
          }
          throw new FyOAException("客户变更授信审批信息写入CRM失败，未知的错误！");
        }
        throw new FyOAException("客户变更授信接口返回XML数据异常，出现多个ErrorMessage");
      }
    }
    catch (DocumentException e)
    {
      throw new FyOAException("解析客户变更授信接口返回XML数据发生异常", e);
    }
  }
  
  public String dealProcessEvent(FySummaryView view, long affairid)
  {
    Customer customer = getCustomerByAffairID(view.getSummaryid(), affairid);
    customer.setAccountfinalstatus("");
    resultParse(send(customer));
    return view.toString();
  }
  
  public String dealFinishEvent(FySummaryView view, long affairid)
  {
    Customer customer = getCustomerByAffairID(view.getSummaryid(), affairid);
    customer.setAccountfinalstatus("生效");
    resultParse(send(customer));
    return view.toString();
  }
  
  public String dealStopEvent(FySummaryView view)
  {
    Customer customer = getCustomer_STOP(view.getSummaryid());
    customer.setAccountfinalstatus("拒绝");
    resultParse(send(customer));
    return view.toString();
  }
  
  public String dealCancelEvent(FySummaryView view, long userid, String message)
  {
    Customer customer = getCustomer_Cancel(view.getSummaryid(), userid, message);
    customer.setAccountfinalstatus("拒绝");
    resultParse(send(customer));
    return view.toString();
  }
  
  public String dealStepBackEvent(FySummaryView view)
  {
    Customer customer = getCustomer_StepBack(view.getSummaryid());
    customer.setAccountfinalstatus("");
    resultParse(send(customer));
    return view.toString();
  }
  
  private String send(Customer customer)
  {
    Document doc = null;
    try
    {
      doc = DocumentHelper.parseText("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cus=\"http://siebel.com/CustomUI\"><soapenv:Header>\n<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">\n<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">\n<wsse:Username>GUESTERM</wsse:Username>\n<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>\n</wsse:UsernameToken>\n</wsse:Security>\n</soapenv:Header>\n   <soapenv:Body>\n      <cus:FYOAApproveServiceAccntChangeApprove_Input>\n         <cus:Accountfinalstatus></cus:Accountfinalstatus>\n         <cus:AccounId></cus:AccounId>\n\t\t\t<cus:Accountmessage></cus:Accountmessage>\n         <cus:Accountposition></cus:Accountposition>\n <cus:RecordId></cus:RecordId>         <cus:Oacreateddatetime></cus:Oacreateddatetime>\n      </cus:FYOAApproveServiceAccntChangeApprove_Input>\n   </soapenv:Body>\n</soapenv:Envelope>");
    }
    catch (DocumentException e)
    {
      throw new FyOAException("解析XML模板失败", e);
    }
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:Accountfinalstatus").get(0)).setText(customer.getAccountfinalstatus());
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:AccounId").get(0))
      .setText(customer.getAccounId());
    
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:Accountmessage").get(0)).setText(customer.getAccountmessage());
    
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:Accountposition").get(0)).setText(customer.getAccountposition());
    
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:Oacreateddatetime").get(0)).setText(customer.getAacreateddatetime());
    ((Element)doc.selectNodes("//cus:FYOAApproveServiceAccntChangeApprove_Input//cus:RecordId").get(0))
      .setText(customer.getRecordId());
    //正式环境
//    return this.fyOA_SOAPClient.post(doc.asXML(),
//      "http://10.111.0.162:7777/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
//      "\"document/http://siebel.com/CustomUI:FYOAApproveServiceAccntChangeApprove\"");
    //测试
    return this.fyOA_SOAPClient.post(doc.asXML(),
            "http://10.112.0.112:7777/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
            "\"document/http://siebel.com/CustomUI:FYOAApproveServiceAccntChangeApprove\"");
  }
  
  private Customer getCustomerByAffairID(long summaryid, long affairid)
  {
    Customer customer = null;
    if (affairid != -1L)
    {
      Map<String, Object> temp = this.jdbcTemplate.queryForMap("select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere (a.AFFAIR_ID,a.CREATE_DATE) in ( select a1.affair_id,max(a1.create_date) from CTP_COMMENT_ALL a1 where a1.AFFAIR_ID=? group by a1.affair_id)  and rownum = 1", new Object[] { Long.valueOf(affairid) });
      if (temp != null)
      {
        customer = new Customer();
        setCustormer(summaryid, customer);
        customer.setAacreateddatetime(getNowTime());
        customer.setAccountposition((String)temp.get("member"));
        customer.setAccountmessage(
          "【" + this.fyOAConf.getDelAttitude((String)temp.get("opinion")) + 
          "】    " + (String)temp.get("msg"));
      }
    }
    else
    {
      customer = new Customer();
      setCustormer(summaryid, customer);
      customer.setAacreateddatetime(getNowTime());
    }
    return customer;
  }
  
  private Customer getCustomer_STOP(long summaryid)
  {
    Customer customer = null;
    Map<String, Object> temp = this.jdbcTemplate.queryForMap("select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.termination' and rownum =1", new Object[] { Long.valueOf(summaryid) });
    if (temp != null)
    {
      customer = new Customer();
      setCustormer(summaryid, customer);
      customer.setAacreateddatetime(getNowTime());
      customer.setAccountposition((String)temp.get("member"));
      customer.setAccountmessage(
        "【" + this.fyOAConf.getDelAttitude((String)temp.get("opinion")) + 
        "】    " + (String)temp.get("msg"));
    }
    return customer;
  }
  
  private Customer getCustomer_Cancel(long summaryid, long userID, String msg)
  {
    Customer customer = null;
    
    String temp = (String)this.jdbcTemplate.queryForObject("select p.NAME||'/'||m.name member from ORG_MEMBER m left join ORG_POST p on m.ORG_POST_ID = p.id where m.id =?", new Object[] { Long.valueOf(userID) }, String.class);
    if (temp != null)
    {
      customer = new Customer();
      setCustormer(summaryid, customer);
      customer.setAacreateddatetime(getNowTime());
      customer.setAccountposition(temp);
      customer.setAccountmessage("【撤销】    " + msg);
    }
    return customer;
  }
  
  private Customer getCustomer_StepBack(long summaryid)
  {
    Customer customer = null;
    
    Map<String, Object> temp = this.jdbcTemplate.queryForMap("select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\nfrom CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \nleft join ORG_POST p on m.ORG_POST_ID = p.id\nwhere a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.rollback' and rownum =1", new Object[] { Long.valueOf(summaryid) });
    if (temp != null)
    {
      customer = new Customer();
      setCustormer(summaryid, customer);
      customer.setAacreateddatetime(getNowTime());
      customer.setAccountposition((String)temp.get("member"));
      customer.setAccountmessage(
        "【" + this.fyOAConf.getDelAttitude((String)temp.get("opinion")) + 
        "】    " + (String)temp.get("msg"));
    }
    return customer;
  }
  
  public String getNowTime()
  {
    Date date = Calendar.getInstance().getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    return sdf.format(date);
  }
  
  public void setCustormer(long summaryid, Customer customer)
  {
    Map<String, String> map = getValues(summaryid);
    customer.setAccounId((String)map.get("客户Id"));
    customer.setRecordId((String)map.get("客户信息变更记录Id"));
  }
  
  public void setFyOA_SOAPClient(FyOA_SOAPClient fyOA_SOAPClient)
  {
    this.fyOA_SOAPClient = fyOA_SOAPClient;
  }
  
  private class Customer
  {
    private String accounId;
    private String accountmessage;
    private String accountposition;
    private String aacreateddatetime;
    private String recordId;
    private String accountfinalstatus;
    
    private Customer() {}
    
    public String toString()
    {
      return 
        "Customer [accounId=" + this.accounId + ", accountmessage=" + this.accountmessage + ", accountposition=" + this.accountposition + ", aacreateddatetime=" + this.aacreateddatetime + ", recordId=" + this.recordId + "]";
    }
    
    public String getAccountfinalstatus()
    {
      return this.accountfinalstatus;
    }
    
    public void setAccountfinalstatus(String accountfinalstatus)
    {
      this.accountfinalstatus = accountfinalstatus;
    }
    
    public String getRecordId()
    {
      return this.recordId;
    }
    
    public void setRecordId(String recordId)
    {
      this.recordId = recordId;
    }
    
    public String getAccounId()
    {
      return this.accounId;
    }
    
    public void setAccounId(String accounId)
    {
      this.accounId = accounId;
    }
    
    public String getAccountmessage()
    {
      return this.accountmessage;
    }
    
    public void setAccountmessage(String accountmessage)
    {
      this.accountmessage = accountmessage;
    }
    
    public String getAccountposition()
    {
      return this.accountposition;
    }
    
    public void setAccountposition(String accountposition)
    {
      this.accountposition = accountposition;
    }
    
    public String getAacreateddatetime()
    {
      return this.aacreateddatetime;
    }
    
    public void setAacreateddatetime(String aacreateddatetime)
    {
      this.aacreateddatetime = aacreateddatetime;
    }
  }
  
  public static void main(String[] args)
  {
    System.out.println("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cus=\"http://siebel.com/CustomUI\"><soapenv:Header>\n<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">\n<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">\n<wsse:Username>GUESTERM</wsse:Username>\n<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>\n</wsse:UsernameToken>\n</wsse:Security>\n</soapenv:Header>\n   <soapenv:Body>\n      <cus:FYOAApproveServiceAccntChangeApprove_Input>\n         <cus:Accountfinalstatus></cus:Accountfinalstatus>\n         <cus:AccounId></cus:AccounId>\n\t\t\t<cus:Accountmessage></cus:Accountmessage>\n         <cus:Accountposition></cus:Accountposition>\n <cus:RecordId></cus:RecordId>         <cus:Oacreateddatetime></cus:Oacreateddatetime>\n      </cus:FYOAApproveServiceAccntChangeApprove_Input>\n   </soapenv:Body>\n</soapenv:Envelope>");
  }
}
